package com.xinfu.newproject.ui.complaint_feedback;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alley.van.VanGogh;
import com.alley.van.helper.VanCropType;
import com.alley.van.helper.VanMediaFilter;
import com.alley.van.helper.VanMediaType;
import com.alley.van.model.VanConfig;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.xinfu.newproject.R;
import com.xinfu.newproject.adapter.matter_repair_adapter.RepairImageAdapter;
import com.xinfu.newproject.base.BaseActivity;
import com.xinfu.newproject.bean.complaint.bean.ComplaintDetailBean;
import com.xinfu.newproject.bean.complaint.bean.ComplaintEvaluateBean;
import com.xinfu.newproject.bean.complaint.bean.ComplaintRecordBean;
import com.xinfu.newproject.bean.complaint.bean.SubmitComplaintBean;
import com.xinfu.newproject.bean.login.LoginBean;
import com.xinfu.newproject.bean.up_image.UpImageBean;
import com.xinfu.newproject.presenter.ComplaintPresenter;
import com.xinfu.newproject.presenter.UpImagePresenter;
import com.xinfu.newproject.test.GifSizeFilter;
import com.xinfu.newproject.test.GlideImageLoader;
import com.xinfu.newproject.test.VanToast;
import com.xinfu.newproject.util.BToast;
import com.xinfu.newproject.util.GetImagePathUtil;
import com.xinfu.newproject.util.SPUtils;
import com.xinfu.newproject.view.IView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

import static com.xinfu.newproject.contants.Constant.LOGIN;
import static com.xinfu.newproject.contants.Contants.REQUEST_CODE_AVATAR;
import static com.xinfu.newproject.contants.Contants.REQUEST_CODE_IMAGE;

public class ComplaintEvaluateActivity extends BaseActivity implements RepairImageAdapter.RemoveOnClickListener, IView.IComplaintView, IView.IUpImageView, TextWatcher {


    @BindView(R.id.layout_up_image_rv)
    RecyclerView imageRecyclerView;

    @BindView(R.id.activity_complaint_evaluate_et)
    EditText evalurateEt;

    @BindView(R.id.activity_complaint_evaluate_input)
    TextView sizeTv;

    @BindView(R.id.activity_complaint_evaluate_yes_tv)
    TextView yesTv;

    @BindView(R.id.activity_complaint_evaluate_no_tv)
    TextView noTv;

    private RepairImageAdapter repairImageAdapter;

    private int imageAdapterCount = 1;
    private int isImage = 0;
    private ArrayList<String> imageList = new ArrayList<>();
    private static final int REQUEST_CODE_CHOOSE = 23;
    private static final int REQUEST_CODE_CAMERA = 32;
    private int status = 300;

    private ComplaintPresenter complaintPresenter = new ComplaintPresenter(this);
    private UpImagePresenter upImagePresenter = new UpImagePresenter(this);

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_complaint_evaluate);
        ButterKnife.bind(this);
        registerBack();
        initView();
        listener();

    }

    private void listener() {
        evalurateEt.addTextChangedListener(this);
    }

    private void initView() {
        setActivityTitle("投诉评价");
        imageRecyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        repairImageAdapter = new RepairImageAdapter(this);
        imageRecyclerView.setAdapter(repairImageAdapter);
        imageList.add(0, "0");
        repairImageAdapter.setNewData(imageList);
        repairImageAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @SuppressLint("CheckResult")
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (imageList.get(position).equals("0")) {
                    isCode = REQUEST_CODE_AVATAR;
                    onClickCamera();
                } else {
                    isCode = REQUEST_CODE_IMAGE;
                    imagePosition = position;
                    onClickCamera();
                }
            }
        });
    }

    int isCode;

    @Override
    public void permissionGrant(boolean isGranted, int requestCode) {
        super.permissionGrant(isGranted, requestCode);
        if (!isGranted) {
            return;
        }
        switch (requestCode) {
            case 0x0001://拍照
                VanGogh.from(ComplaintEvaluateActivity.this)
                        .choose(VanMediaType.ofAll())//拍照时，无效
                        .cameraVisible(true, getPackageName())//拍照时，第一个参数无效
                        .withResultSize(1024, 1024)
                        .cropEnable(false, VanCropType.CROP_TYPE_RECTANGLE)//第一个参数为FALSE时，第二个参数无效
                        .theme(R.style.VanTheme_ActivityAnimation)
                        .thumbnailScale(0.85f)
                        .toast(new VanToast())
                        .imageLoader(new GlideImageLoader())
                        .forCamera(REQUEST_CODE_CAMERA);
                break;

            case 0x0002://从相册选择
                int maxCount;
                if (isCode == REQUEST_CODE_AVATAR) {
                    maxCount = 5 - imageList.size();
                } else {
                    maxCount = 4;
                }
                VanGogh.from(ComplaintEvaluateActivity.this)
                        .choose(VanMediaType.ofAll())
                        .countable(true)//若开启裁剪，则无效
                        .maxCount(maxCount)
                        .rowCount(3)
                        .cameraVisible(true, getPackageName())//设置在第一个参数为FALSE时，第二个参数无效
                        .withResultSize(1024, 1024)
                        .cropEnable(false, VanCropType.CROP_TYPE_RECTANGLE)//第一个参数为TRUE时，则可选中数量被设为1，此时maxSelectable(9)无效；第一个参数为FALSE时，第二个参数无效
                        .theme(R.style.VanTheme_Dracula)
                        .addFilter(new GifSizeFilter(320, 320, 5 * VanMediaFilter.K * VanMediaFilter.K))
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                        .thumbnailScale(0.85f)
                        .toast(new VanToast())
                        .imageLoader(new GlideImageLoader())
                        .forResult(REQUEST_CODE_CHOOSE);
                break;

            default:
                break;
        }
    }

    @OnClick({R.id.activity_complaint_evaluate_btn, R.id.activity_complaint_evaluate_yes_tv, R.id.activity_complaint_evaluate_no_tv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.activity_complaint_evaluate_btn:
                if (TextUtils.isEmpty(evalurateEt.getText())) {
                    BToast.showText(this, "请填写评价内容");
                } else {
                    if (isLogin(0) && getIntent().getExtras().getString("response") != null) {
                        showLoding();
                        if (imageList.size() > 0) {
                            if (isImage == 1) {
                                upImagePresenter.upImage();
                            } else {
                                complaintPresenter.complaintEvaluate();
                            }
                        } else {
                            complaintPresenter.complaintEvaluate();
                        }
                    }
                }

                break;
            case R.id.activity_complaint_evaluate_yes_tv:
                status = 300;
                yesTv.setTextColor(getResources().getColor(R.color.white));
                yesTv.setBackgroundResource(R.drawable.invoice_yes_bg_press);
                noTv.setTextColor(getResources().getColor(R.color.yellow_ff));
                noTv.setBackgroundResource(R.drawable.invoice_no_bg);
                break;
            case R.id.activity_complaint_evaluate_no_tv:
                status = 400;
                yesTv.setTextColor(getResources().getColor(R.color.yellow_ff));
                yesTv.setBackgroundResource(R.drawable.invoice_yes_bg);
                noTv.setTextColor(getResources().getColor(R.color.white));
                noTv.setBackgroundResource(R.drawable.invoice_no_bg_press);
                break;
        }
    }

    /**
     * 判断是否可以请求数据
     */
    String token, userId, userName;

    private boolean isLogin(int type) {

        LoginBean.ResultBean resultBean;
        String responseIntent = (String) SPUtils.get(this, LOGIN, "0");
        if (!responseIntent.equals("0")) {
            resultBean = new Gson().fromJson(responseIntent, LoginBean.ResultBean.class);
            token = resultBean.getToken();
            userId = resultBean.getUserInfo().getId();
            userName = resultBean.getUserInfo().getUsername();
        } else {
            return false;
        }


        return true;
    }

    /**
     * 删除选择的图片
     *
     * @param position
     */
    @Override
    public void removeImage(int position) {
        imageList.remove(position);
        for (int i = 0; i < imageList.size(); i++) {
            if (imageList.get(i).equals("0")) {
                imageList.remove(i);
            }
        }
        if (imageList.size() < 4) {
            imageList.add("0");
        }
        repairImageAdapter.setNewData(imageList);
    }

    Integer imagePosition;
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            final ArrayList<String> pathList = new ArrayList<>();
            switch (requestCode) {
                case REQUEST_CODE_CHOOSE:
                    if (VanGogh.obtainResult(data) != null) {
                        if (VanGogh.obtainResult(data).size() > 0) {
                            for (int i = 0; i < VanGogh.obtainResult(data).size(); i++) {
                                pathList.add(GetImagePathUtil.getRealFilePath(this, VanGogh.obtainResult(data).get(i)));
                            }
                        }
                    }
                    if (isCode == REQUEST_CODE_AVATAR) {
                        if ((imageList.size() - 1) < pathList.size()) {
                            if (imageList.size() == 1) {
                                imageList.clear();
                            } else {
                                imageList.remove(imageList.size() - 1);
                            }
                            for (int i = 0; i < pathList.size(); i++) {
                                imageList.add(i, pathList.get(i));
                            }
                        } else if ((5 - imageList.size()) >= pathList.size()) {
                            if (imageList.size() == 1) {
                                imageList.clear();
                            } else {
                                imageList.remove(imageList.size() - 1);
                            }
                            for (int i = 0; i < pathList.size(); i++) {
                                imageList.add(pathList.get(i));
                            }
                        }
                        isImage = 1;
                    } else {
                        if (pathList != null) {
                            if (pathList.size() > 0) {
                                if (pathList.size() == 1 && !pathList.get(0).equals("")) {
                                    if (imagePosition != null) {
                                        imageList.set(imagePosition, pathList.get(0));
                                    }
                                } else {
                                    if (!pathList.get(0).equals("")) {
                                        imageList.clear();
                                        for (int i = 0; i < pathList.size(); i++) {
                                            imageList.add(i, pathList.get(i));
                                        }
                                    }
                                }
                            }
                        }
                        imagePosition = null;
                        isImage = 1;
                    }
                    break;
                case REQUEST_CODE_CAMERA:

                    Uri contentUri = VanGogh.obtainCamera();
                    if (contentUri == null) {
                        return;
                    }

                    if (!VanConfig.getInstance().cropEnable) {

                        pathList.add(GetImagePathUtil.getRealFilePath(this, contentUri));
                    }
                    if (isCode == REQUEST_CODE_AVATAR) {
                        if ((imageList.size() - 1) < pathList.size()) {
                            if (imageList.size() == 1) {
                                imageList.clear();
                            } else {
                                imageList.remove(imageList.size() - 1);
                            }
                            for (int i = 0; i < pathList.size(); i++) {
                                imageList.add(i, pathList.get(i));
                            }
                        } else if ((5 - imageList.size()) >= pathList.size()) {
                            if (imageList.size() == 1) {
                                imageList.clear();
                            } else {
                                imageList.remove(imageList.size() - 1);
                            }
                            for (int i = 0; i < pathList.size(); i++) {
                                imageList.add(pathList.get(i));
                            }
                        }
                        isImage = 1;
                    } else {
                        if (pathList != null) {
                            if (pathList.size() > 0) {
                                if (pathList.size() == 1 && !pathList.get(0).equals("")) {
                                    if (imagePosition != null) {
                                        imageList.set(imagePosition, pathList.get(0));
                                    }
                                } else {
                                    if (!pathList.get(0).equals("")) {
                                        imageList.clear();
                                        for (int i = 0; i < pathList.size(); i++) {
                                            imageList.add(i, pathList.get(i));
                                        }
                                    }
                                }
                            }
                        }
                        imagePosition = null;
                        isImage = 1;
                    }
                    break;
            }
            for (int i = 0; i < imageList.size(); i++) {
                if (imageList.get(i).equals("0")) {
                    imageList.remove(i);
                }
            }
            if (imageList.size() < 4) {
                imageList.add("0");
            }
            repairImageAdapter.setNewData(imageList);
        }
    }

    @Override
    public String header() {
        return token;
    }

    @Override
    public List<String> imageList() {
        return imageList;
    }

    @Override
    public Context context() {
        return this;
    }

    @Override
    public String userId() {
        return null;
    }

    @Override
    public String type() {
        return null;
    }

    @Override
    public String name() {
        return userName;
    }

    @Override
    public String telephone() {
        return null;
    }

    @Override
    public String picture() {
        return attachFile;
    }

    @Override
    public String content() {
        return evalurateEt.getText().toString().trim();
    }

    @Override
    public String projectId() {
        return null;
    }

    @Override
    public String complaintId() {
        ComplaintRecordBean.ResultBean resultBean1 = new Gson().fromJson(getIntent().getExtras().getString("response"), ComplaintRecordBean.ResultBean.class);
        return resultBean1.getId();
    }

    @Override
    public String tenantId() {
        ComplaintRecordBean.ResultBean resultBean1 = new Gson().fromJson(getIntent().getExtras().getString("response"), ComplaintRecordBean.ResultBean.class);
        return resultBean1.getTenantId();
    }

    @Override
    public Integer status() {
        return status;
    }

    @Override
    public void showToast(String content) {
        BToast.showText(this, content);
    }

    @Override
    public void closeDispose(Disposable disposable) {

    }

    @Override
    public void showProgress() {
        showLoding();
    }

    @Override
    public void hideProgress() {
        hideLoding();
    }

    @Override
    public void getMsg(SubmitComplaintBean submitComplaintBean) {

    }

    @Override
    public void getMsg(ComplaintRecordBean complaintRecordBean) {

    }

    @Override
    public void getMsg(ComplaintDetailBean complaintDetailBean) {

    }

    @Override
    public void getMsg(ComplaintEvaluateBean complaintEvaluateBean) {
        BToast.showText(this, complaintEvaluateBean.getMessage());
        finish();
    }

    String attachFile = "";

    @Override
    public void getData(UpImageBean upImageBean) {
        attachFile = upImageBean.getResult();
        Log.i("testImage", isImage + "");
        if (attachFile != null) {
            if (isImage == 1) {
                complaintPresenter.complaintEvaluate();
            } else {
                BToast.showText(this, "请上传图片");
            }
        }
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        sizeTv.setText((200 - evalurateEt.getText().length()) + "/200");
        if (evalurateEt.getText().length() == 200) {
            BToast.showText(this, "字数已达上限");
        }
    }
}